package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import sun.security.krb5.internal.PAData;

import java.util.List;
import java.util.Optional;

@Service
public class BannerServiceImpl implements IBannerService {
    @Autowired
    private BannerRepository bannerRepository;
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void insert(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public Banner findById(String id) {
        Optional<Banner> banner = bannerRepository.findById(id);
        return banner.orElse(null);
    }

    @Override
    public List<Banner> findAll() {
        List<Banner> all = bannerRepository.findAll();
        return all;
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {
        Query query = new Query();

        //先判断是否有数据
        long total = mongoTemplate.count(query, Banner.class);

        if (total == 0){
            return Page.empty();
        }

        //拼接条件进行当前页的数据查询
        Pageable request = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "type");
        query.with(request);
        List<Banner> regions = mongoTemplate.find(query, Banner.class);

        //给予三个参数返回的是一个类似PageResult
        return new PageImpl<>(regions, request, total);
    }

    @Override
    public List<Banner> findTravelByType() {
        //前五篇
        //Pageable pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "sequence");
        //类型为游记,而且状态是正常的
        return bannerRepository.findByTypeAndState(Banner.TYPE_TRAVEL,Banner.STATE_NORMAL,PageRequest.of(0, 5, Sort.Direction.ASC, "sequence"));
    }

    @Override
    public List<Banner> findStrategyByType() {
        //前五篇
        //Pageable pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "sequence");
        //类型为攻略,而且状态是正常的
        return bannerRepository.findByTypeAndState(Banner.TYPE_STRATEGY,Banner.STATE_NORMAL,PageRequest.of(0, 5, Sort.Direction.ASC, "sequence"));
    }


}
